package com.deyuanyun.pic.pipe.controller;

import com.caixu.beanvalidateutil.imlclass.BeanValidateUtil;
import com.caixu.beanvalidateutil.imlclass.VResult;
import com.deyuanyun.pic.common.dto.PageJsonBean;
import com.deyuanyun.pic.common.tool.StaticParam;
import com.deyuanyun.pic.common.util.MyCollectionUtil;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.RequestUtil;
import com.deyuanyun.pic.common.util.ajax.AjaxResponse;
import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import com.deyuanyun.pic.common.util.poi.ReadExcel;
import com.deyuanyun.pic.common.util.poi.WriteExcel;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.pipe.controller.publiccontroller.DownLoadController;
import com.deyuanyun.pic.pipe.domain.custom.CustomPicPipeTrackPoint;
import com.deyuanyun.pic.pipe.domain.exceldomain.TrackPointExcelExportVO;
import com.deyuanyun.pic.pipe.domain.exceldomain.TrackPointExcelImportVO;
import com.deyuanyun.pic.pipe.service.PipeTrackPointService;
import com.deyuanyun.pic.pipe.support.other.QueryParamUtil;
import com.deyuanyun.pic.support.utils.ExcelUtils;
import com.deyuanyun.pic.pipe.support.utils.UniformCodeUtils;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xu on 2016/1/22.
 */
@Controller
@RequestMapping("pipe/data/trackPoint/")
public class PipeTrackPointController extends PipeBaseController {
    static Logger logger=Logger.getLogger(PipeTrackPointController.class);
    @Autowired
    private PipeTrackPointService pipeTrackPointService;

    /**
     * 删除标识点
     * @param id
     */
    @RequestMapping("delTrackPoint.json")
    @ResponseBody
    public void delTrackPoint(String id){
        Asserts.assertTrue(StringUtils.isNotBlank(id),"删除id不能为空");
        pipeTrackPointService.delTrackPoint(id);
        AjaxSupport.sendSuccessText("success","success");
    }

    /**
     * 查询跟踪点
     * @param pipeLineId
     * @param segmentId
     * @param juliStart
     * @param juliEnd
     * @throws Exception
     */
    @RequestMapping("queryTrackPointList.json")
    @ResponseBody
    public void queryTrackPointList(String pipeLineId,String segmentId,String juliStart,String juliEnd)throws Exception{
        Map map=new HashMap();
        map.put("pipeLineId",pipeLineId);
        map.put("segmentId",segmentId);
        QueryParamUtil.queryJuLiMap(juliStart,juliEnd,map);
        PageJsonBean jsonBean=new PageJsonBean();
        List<CustomPicPipeTrackPoint> customPicPipeTrackPointList = pipeTrackPointService.queryTrackPointList(map);
        jsonBean.setList(customPicPipeTrackPointList);
        AjaxSupport.sendSuccessText("success",jsonBean);
    }

    /**
     * 导入excel
     * @param multipartFiles
     * @param response
     * @throws Exception
     */
    @RequestMapping("trackPointImport.json")
    @ResponseBody
    public void trackPointImport(@RequestParam("file")MultipartFile[] multipartFiles, HttpServletResponse response)throws Exception{
        Asserts.assertTrue(!ObjectUtil.isEmptyAll(multipartFiles),"附件不能为空");
        List<TrackPointExcelImportVO> xx= ReadExcel.readExcle(TrackPointExcelImportVO.class,multipartFiles[0].getInputStream(),3,"12");
        List<TrackPointExcelImportVO> finalInfo= MyCollectionUtil.removeLastEmpty(xx);
        VResult b= BeanValidateUtil.vali2(finalInfo,3+"");

        if (b.isRelult()){
            finalInfo=UniformCodeUtils.sortedByLine(finalInfo,"pipeLineId","","code","定标点");
            pipeTrackPointService.insertTrackPoint(finalInfo);
            AjaxResponse.sendText(response, StaticParam.UPLOAD_FILE_SUCCESS);
        }else {
            String[] titleArr= ReadExcel.getTitle(multipartFiles[0],"in/track_point_t.xls");
            String m=b.getAllString(titleArr);
            response.setStatus(503);
            AjaxResponse.sendText(response,StaticParam.getUploadFileFailMessage(m));
        }
        return;
    }

    @RequestMapping("trackPointExport.json")
    @ResponseBody
    @Deprecated
    public void trackPointExport(HttpServletResponse response,String pipeLineId,String segmentId,String juliStart,String juliEnd)throws Exception{
        Map map=new HashMap();
        map.put("pipeLineId",pipeLineId);
        map.put("segmentId",segmentId);
        QueryParamUtil.queryJuLiMap(juliStart,juliEnd,map);
        map.put("isConvert","false");
        List<CustomPicPipeTrackPoint> customPicPipeTrackPointList = pipeTrackPointService.queryTrackPointList(map);
        List<TrackPointExcelExportVO> excelMarkPointExportVOs=new ArrayList<>();
        List<TrackPointExcelExportVO> excelYDGZDPointExportVOs=new ArrayList<>();
        List<TrackPointExcelExportVO> excelTZDPointExportVOs=new ArrayList<>();

        for (CustomPicPipeTrackPoint customPicPipeTrackPoint:customPicPipeTrackPointList){
            if ("1E3290704BF1749EE0530E0AA8C06101".equals(customPicPipeTrackPoint.getType())){
                excelMarkPointExportVOs.add(customPicPipeTrackPoint.toExportVO());
            }else if ("1E3290704BF1749EE0530E0AA8C06102".equals(customPicPipeTrackPoint.getType())){
                excelYDGZDPointExportVOs.add(customPicPipeTrackPoint.toExportVO());
            }else if ("1E3290704BF1749EE0530E0AA8C06103".equals(customPicPipeTrackPoint.getType())){
                excelTZDPointExportVOs.add(customPicPipeTrackPoint.toExportVO());
            }

        }
        String templateName="out/trackPoint_template.xls";
        Workbook workbook=ReadExcel.readExcelTemplate(templateName);
        Workbook workbookFinal = WriteExcel.writeExcel(workbook,excelMarkPointExportVOs,1, Lists.<String>newArrayList("priUuid","type","mileage","referenceDistance"));
        DownLoadController.initExcelDownResponse(response,StringUtils.removeEnd(templateName,"Template"));
        DownLoadController.excelOut(response,workbookFinal);
        return;
    }

    @RequestMapping("trackPointExport2.json")
    @ResponseBody
    public void trackPointExport2(HttpServletResponse response, HttpServletRequest request)throws Exception{
        HashMap data= RequestUtil.parseRequestParamToHashMap(request);
        List<List<String[]>> result = pipeTrackPointService.exportExcel(data);

        InputStream filePath = this.getClass().getResourceAsStream("/template/out/trackPoint_template.xls");
        // 将Object中存的List取出
        int[] lineStart = new int[] { 1 };
        ExcelUtils.jxlExportExcel(filePath, lineStart, "定标点", result, response);
        return;
    }
}
